<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'

// 图片地址数组
const imgs = [
  "src/assets/imgs/1.jpeg",
  "src/assets/imgs/2.jpeg",
  "src/assets/imgs/3.jpeg",
]

// 用于绑定的当前图片地址
const imgurl = ref(imgs[0])

// 当前显示的图片索引
const index = ref(0)

// 上一张
const prevclick = () => {
  index.value = (index.value - 1 + imgs.length) % imgs.length
  imgurl.value = imgs[index.value]
}

// 下一张
const nextclick = () => {
  index.value = (index.value + 1) % imgs.length
  imgurl.value = imgs[index.value]
}

// 定时器
let timer = null

// 启动定时器
const startTimer = () => {
  timer = setInterval(() => {
    nextclick()
  }, 3000)
}

// 停止定时器
const stopTimer = () => {
  clearInterval(timer)
}

// 组件挂载时启动定时器
onMounted(() => {
  startTimer()
})

// 组件卸载时停止定时器
onUnmounted(() => {
  stopTimer()
})

// 点击小圆点
const dotclick = (i) => {
  index.value = i
  imgurl.value = imgs[index.value]
}
</script>

<template>
  <div class="carousel">
    <img :src="imgurl" alt="">
    <span class="prev" @click="prevclick">&lt;</span>
    <span class="next" @click="nextclick">&gt;</span>

    <div class="dots">
      <!-- 使用v-for生成小圆点 -->
      <span
        v-for="(img, i) in imgs"
        :key="i"
        class="dot"
        :class="{ active: index === i }"
        @click="dotclick(i)"
      ></span>
    </div>
  </div>
</template>

<style>
.carousel {
  width: 1000px;
  height: 240px;
  overflow: hidden;
  position: relative;
  margin: 0 auto;
}
.carousel img {
  width: 1000px;
  height: 240px;
}
.carousel .prev, .carousel .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 10px;
  cursor: pointer;
}
.carousel .prev {
  left: 0;
}
.carousel .next {
  right: 0;
}
.dots {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}
.dot {
  width: 10px;
  height: 10px;
  background-color: rgba(255,255,255,0.5);
  border-radius: 50%;
  margin: 0 5px;
  cursor: pointer;
}
/* 当前小圆点的样式 */
.dot.active {
  background-color: #fff;
}
</style>